const data = [{
    id: 1,
    count: 2,
    price: 12.5
}, {
    id: 2,
    count: 0,
    price: 10.5
}, {
    id: 3,
    count: 3,
    price: 8.5
}, {
    id: 4,
    count: 0,
    price: 8
}, {
    id: 5,
    count: 0,
    price: 14.5
}];

let computedBox = document.querySelector('#computedBox'),
    topBox = computedBox.querySelector('.top'),
    [countsBox, pricesBox] = Array.from(computedBox.querySelectorAll('.bottom span')),
    pronumsBox = [],
    emsBox = [];

// 动态绑定数据
const render = () => {
    let str = ``;
    data.forEach((item, index) => {
        let { count, price } = item;
        str += `<div class="hang" index="${index}">
            <i class="minus"></i>
            <span class="pronum">${count}</span>
            <i class="add"></i>
            <span class="info">
                单价：${price}元 &nbsp;&nbsp;
                小计：<em>${count * price}</em>元
            </span>
        </div>`;
    });
    topBox.innerHTML = str;

    // 获取DOM元素
    pronumsBox = Array.from(topBox.querySelectorAll('.pronum'));
    emsBox = Array.from(topBox.querySelectorAll('em'));
};
render();

// 计算总计信息
const computed = () => {
    let counts = 0,
        prices = 0;
    pronumsBox.forEach((pronum, index) => {
        counts += +pronum.innerHTML;
        prices += +emsBox[index].innerHTML;
    });
    countsBox.innerHTML = counts;
    pricesBox.innerHTML = prices;
};
computed();

// 事件委托
topBox.addEventListener('click', function (ev) {
    let target = ev.target;
    if (target.tagName === 'I') {
        let index = +target.parentNode.getAttribute('index'),
            pronumBox = pronumsBox[index],
            emBox = emsBox[index],
            price = data[index].price,
            count = +pronumBox.innerHTML;
        if (target.className === 'minus') {
            count--;
            if (count < 0) count = 0;
        } else {
            count++;
        }
        pronumBox.innerHTML = count;
        emBox.innerHTML = count * price;
        computed();
    }
});